"use client";
// 显示 layout
import Alert from "./alert";
import { useEffect, useState } from "react";
import { getAll, remove, getColumnData } from "../action/orm";
import { v4 as uuidv4 } from "uuid";
import Toolbar from "./toolbar";
import Popup from "./popup";
import Context from "./context";

// meta 是定义页面的元数据
export default function Table({ define }) {
  const [select, SetSelect] = useState(null); // 选择的记录ID
  const [data, SetData] = useState([]); //表单数据
  const [loaded, SetLoaded] = useState(false); // 是否已经加载数据
  const [operator, SetOperator] = useState("add"); // 弹出窗口的操作类型，增加或编辑
  const [alertMsg, SetAlertMsg] = useState(""); // 提示信息
  const [meta, SetMeta] = useState({}); // 表单元数据

  // 获取所有数据
  const getData = async () => {
    SetData(await getAll(define.table, define.relation, ["id", "name"]));
    SetLoaded(true);
  };

  // 读取 Meta Form 中 list 的数据，增加到对应 item 中
  const addListData = async (item) => {
    const formData = item["form"];

    formData.forEach(async (item) => {
      if (item.type === "list") {
        const [table, column] = item.source.split(".");
        item.data = await getColumnData(table, column);
      }
    });

    SetMeta(item);
  };

  // 初始化数据
  useEffect(() => {
    getData();

    addListData(define);

    SetMeta(define);
  }, []);

  // 显示弹出对话框
  const showPopup = (ifShow) => {
    ifShow
      ? document.getElementById("popup-dialog").showModal()
      : document.getElementById("popup-dialog").close();
  };

  const popupDialog = (operator) => {
    // 设置操作类型
    SetOperator(operator);

    // 显示弹出对话框
    showPopup(true);

    // 取消选择
    SetSelect(null);
  };

  const deleteEvent = () => {
    if (select === null) {
      showAlert("请选择一个" + meta.name + "。");
      return;
    }

    deleteRouter(select);

    // 删除数据
    remove(meta.table, "id", select);

    // 刷新数据
    getData();
  };

  // 选择记录
  const selectEvent = (id) => {
    SetSelect(id);
    switchAlert("", false);
  };

  // 处理弹出对话框的提交
  const popupSubmit = (e) => {};

  const resetForm = () => {};

  // 显示或者隐藏信息, ifShow 为 true 显示，false 隐藏
  const switchAlert = (msg, ifShow) => {
    if (ifShow) {
      // 显示信息
      SetAlertMsg(msg);
      document.getElementById("table_alert").classList.remove("hidden");

      // 2 秒后错误信息
      setTimeout(() => {
        SetAlertMsg("");
        document.getElementById("table_alert").classList.add("hidden");
      }, 2000);
    } else {
      // 检查信息是否已经隐藏
      if (alertMsg === "") return;

      // 隐藏信息
      SetAlertMsg("");
      document.getElementById("table_alert").classList.add("hidden");
    }
  };

  return (
    <div>
      {loaded ? (
        <Context.Provider value={{ data, select, meta, operator }}>
          <div>
            <dialog id="popup-dialog" className="modal">
              <Popup
                handleSubmit={popupSubmit}
                operator={operator}
                showPopup={showPopup}
                switchAlert={switchAlert}
              />
            </dialog>

            <section className="card col-span-12 mt-2 overflow-hidden bg-base-100 p-4 shadow-sm xl:col-span-7">
              <Toolbar
                deleteEvent={deleteEvent}
                popupDialog={popupDialog}
                title={meta.title}
                subtitle={meta.subtitle}
                refresh={getData}
              />
              <div id="table_alert" className="hidden">
                <Alert message={alertMsg} />
              </div>
              <div className="overflow-x-aut4 m-4">
                <table className="table table-pin-rows table-pin-cols">
                  <thead>
                    <tr>
                      {meta.columns.map((item) => (
                        <th key={uuidv4()}>{item.lable}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {data &&
                      data.map((item) => (
                        <tr
                          key={item.id}
                          onClick={() => selectEvent(item.id)}
                          className={select === item.id ? "bg-base-200" : ""}
                        >
                          {meta.columns.map((column, index) => (
                            <td key={item.id + index + 10}>
                              {
                                // item 如果存在 table 属性，说明是一个关联表。则获取关联表的名称字段 name
                                item[column.table] && item[column.table].name
                                  ? item[column.table].name
                                  : item[column.name]
                              }
                            </td>
                          ))}
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
            </section>
          </div>
        </Context.Provider>
      ) : (
        <div>loading...</div>
      )}
    </div>
  );
}
